import * as util from "../util"
import * as Service from "./Service"

const handle: util.ConsoleHandle = {
    list(command: util.ConsoleCommandData) {
        if (Service.userList.length === 0) {
            util.logInConsole('当前无人在线');
        } else {
            util.logInConsole('当前用户列表:');
            console.table(Service.userList.map(user => {
                return {
                    name: user.name,
                    id: user.id,
                    ip: user.ip
                }
            }))
            util.logInConsole(`共 ${Service.userList.length} 人在线`);
        }
    },
    exit(command: util.ConsoleCommandData) {
        if (!Service.server.value) {
            process.exit(0);
        }
        util.logInConsole('正在关闭服务器...')
        Service.userList.forEach(user => {
            user.socket.write(util.SERVER_CLOSE_MESSAGE)
            user.socket.end();
        })
        Service.server.value.close(() => {
            util.logInConsole('服务器已关闭');
            process.exit(0);
        });
    }
}

handle.list.command = Service.ConsoleCommand.LIST
handle.exit.command = Service.ConsoleCommand.EXIT

export default handle